/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sip;


/**
 *
 * @author arianareyessantiago
 */
//This class checks the status of the Insulin Sensor and the Battery every 30 seconds.
public class CheckBatteryThread implements Runnable{

    CheckStatus check = new CheckStatus();
    Alarm alarm = new Alarm();
    private static volatile boolean running = true;
    //first element is fatal flag and second is low flag
    boolean[] batteryFlag;
    private int checkIntervalInSeconds;
    private int sleepIntervalInSeconds; //5 minutes
    private int secondsPassed;
    //int alarmInterval;
    
   
    @Override
    public void run(){
        batteryFlag = new boolean[2];
        checkIntervalInSeconds = 1;
        sleepIntervalInSeconds = 300;
        secondsPassed = 300;
        //SipLogger.Instance().debug( "I am in batteryThread.");       
        
        //alarmInterval = 300;
        while(running){
            //System.out.println("I am in batteryThread in running.");
            batteryFlag = check.checkBattery();
            if(batteryFlag[0] == false){
                // Not fatal
                //System.out.println("batteryFatalFlag is false");
               if(batteryFlag[1] == true){
                   // Warning
                   secondsPassed++;
                   if( secondsPassed >= sleepIntervalInSeconds)  {
                    alarm.setAlarm("You Battery is Low!.");
                    secondsPassed = 0;
                   }
                   //System.out.println("batteryLowFlag is true");
                   //try{
                   //    Thread.sleep(sleepIntervalInSeconds*1000);
                    //}catch(InterruptedException e){ 
                     //   SipLogger.Instance().debug("CheckBatteryThread has been Interrupted");
                    //} 
               }
            }
            else if(batteryFlag[0] == true){
                // Fatal
                try{
                    Thread.sleep(10*1000);
                }catch(InterruptedException e){ 
                    SipLogger.Instance().debug("CheckBatteryThread has been Interrupted");
                }
                System.exit(1);
                //SimpleInsulinPumpUI.dispose();
            }
            //SipLogger.Instance().info("Battery was checked.");
            
            try{
                Thread.sleep(checkIntervalInSeconds*1000);
            }
            catch(InterruptedException e){   
            }

        }
        SipLogger.Instance().debug("CheckBatteryThread has stopped.");
    }
    
    public void terminate(){
        SipLogger.Instance().debug("CheckBatteryThread has been Terminated");
        running = false;
    }
}


